<!--
 * Description: PBM报价组件
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/06/1 13:30
-->

<template>
  <div class="fd-quote-edit-pane">
    <!--TODO: 设置用户的习惯按钮 -->
    <el-tooltip class="item" content="自定义表格显示列" effect="dark" placement="top">
      <button class="set-fd-cell" @click="setDialogVisible = true"></button>
    </el-tooltip>
    <div class="custom-top">
      <div class="btn">
        <div class="left">
          <el-link icon="el-icon-folder-checked" @click="saveAll">
            {{ $t('button.submit') }}
          </el-link>
          <el-link icon="el-icon-download" style="margin-left: 15px" @click="rowDown">
            {{ $t('FdData.exportExcel') }}
          </el-link>
          <el-link icon="el-icon-upload2" style="margin-left: 15px" @click="uploadFile">
            {{ $t('FdData.importExcel') }}
          </el-link>
          <input ref="inputfile" class="upload" type="file" @change="inputfileChange" />
        </div>
      </div>
      <div class="total-result">
        <table>
          <tr>
            <td>总行数：{{ totalResult.totalLen }}</td>
            |
            <td>当前行数：{{ totalResult.currentLen }}</td>
            |
            <td>Cost Down：{{ totalResult.costDown }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div v-loading="isRequesting" class="custom-bottom">
      <VirtualTable
        :cb="totalCb"
        cbArgs="costDown"
        :filterable="true"
        :header-cell-style="$headerCellStyle"
        :rowStyle="rowStyle"
        rowKey="fdRowId"
        :table="shareDataList"
      >
        <!-- rowNo -->
        <Cell fix="left" :label="$t('ecdfc.rowNo')" :width="50">
          <template slot-scope="scope">
            <span>{{ scope.index + 1 }}</span>
          </template>
        </Cell>
        <!-- rdFunction -->
        <Cell
          v-if="cellIsShow.IsRDFunction"
          :label="$t('ecdfc.rdFunction')"
          prop="rdFunction"
          sort
        />
        <!-- category -->
        <Cell v-if="cellIsShow.IsCategory" :label="$t('ecdfc.category')" prop="category" sort />
        <!-- fdDesign -->
        <Cell v-if="cellIsShow.IsFdDesign" :label="$t('ecdfc.fdDesign')" prop="fdDesign" sort />
        <!-- Old -->
        <Cell :label="$t('ecdfc.old')">
          <!-- oldPn -->
          <Cell v-if="cellIsShow.IsOldPn" :label="$t('ecdfc.pn')" prop="oldPn" sort />
          <!-- oldQty -->
          <Cell v-if="cellIsShow.IsOldQty" :label="$t('ecdfc.qty')" prop="oldQty" sort />
        </Cell>
        <!-- New -->
        <Cell :label="$t('ecdfc.new')">
          <!-- newPn -->
          <Cell v-if="cellIsShow.IsNewPn" :label="$t('ecdfc.pn')" prop="newPn" sort="number" />
          <!-- newQty -->
          <Cell v-if="cellIsShow.IsNewQty" :label="$t('ecdfc.qty')" prop="newQty" sort="number" />
        </Cell>
        <!-- riskImpact -->
        <Cell
          v-if="cellIsShow.IsRiskImpact"
          :label="$t('ecdfc.riskImpact')"
          prop="riskImpact"
          sort="number"
        />
        <!-- deadline -->
        <Cell
          v-if="cellIsShow.IsDeadline"
          :label="$t('ecdfc.deadline')"
          prop="deadline"
          sort="number"
        />
        <!-- plan -->
        <Cell v-if="cellIsShow.IsPlan" :label="$t('ecdfc.plan')" prop="plan" sort />
        <!-- subject -->
        <Cell v-if="cellIsShow.Issubject" :label="$t('ecdfc.subject')" prop="subject" sort />
        <!-- commodity -->
        <Cell v-if="cellIsShow.Iscommodity" :label="$t('ecdfc.commodity')" prop="commodity" sort />
        <!-- assignedTime -->
        <Cell
          v-if="cellIsShow.IsassignedTime"
          :label="$t('ecdfc.assignedTime')"
          prop="assignedTime"
          sort
        />
        <!-- isAssigned -->
        <Cell v-if="cellIsShow.IsisAssigned" :label="$t('ecdfc.isAssigned')" prop="isAssigned" sort>
          <template slot-scope="scope">
            <span>{{ scope.row.isAssigned ? 'Y' : 'N' }}</span>
          </template>
        </Cell>
        <!-- isGcmCommit -->
        <Cell
          v-if="cellIsShow.IsisGcmCommit"
          :label="$t('ecdfc.isGcmCommit')"
          prop="isGcmCommit"
          sort
        >
          <template slot-scope="scope">
            <span>{{ scope.row.isGcmCommit ? 'Y' : 'N' }}</span>
          </template>
        </Cell>
        <!-- isGcmReject -->
        <Cell
          v-if="cellIsShow.IsisGcmReject"
          :label="$t('ecdfc.isGcmReject')"
          prop="isGcmReject"
          sort
        >
          <template slot-scope="scope">
            <span>{{ scope.row.isGcmReject ? 'Y' : 'N' }}</span>
          </template>
        </Cell>
        <!-- owner -->
        <Cell v-if="cellIsShow.IsOwner" :label="$t('ecdfc.owner')" prop="owner" sort />
        <!-- initialDate -->
        <Cell
          v-if="cellIsShow.IsInitialDate"
          :label="$t('ecdfc.initialDate')"
          prop="initialDate"
          sort="number"
        />
        <!-- closeDate -->
        <Cell
          v-if="cellIsShow.IsCloseDate"
          :label="$t('ecdfc.closeDate')"
          prop="closeDate"
          sort="number"
        />
        <!-- svtBomStatus -->
        <Cell
          v-if="cellIsShow.IsSvtBomStatus"
          :label="$t('ecdfc.svtBomStatus')"
          prop="svtBomStatus"
          sort="number"
        />
        <!-- rdForecastCost -->
        <Cell
          v-if="cellIsShow.IsRdForecastCost"
          :label="$t('ecdfc.rdForecastCost')"
          prop="rdForecastCost"
          sort="number"
        />
        <!-- costDown -->
        <Cell
          v-if="cellIsShow.IsCostDown"
          :label="$t('ecdfc.costDown')"
          prop="costDown"
          sort="number"
        />
        <!-- apprvoal -->
        <Cell v-if="cellIsShow.IsApprvoal" :label="$t('ecdfc.apprvoal')" prop="apprvoal" sort />
        <!-- remark -->
        <Cell v-if="cellIsShow.IsRemark" :label="$t('ecdfc.remark')" prop="remark" />
        <!-- gcm -->
        <Cell :label="$t('FdData.gcm')">
          <!-- gcmFunction -->
          <Cell
            v-if="cellIsShow.IsGcmFunction"
            :label="$t('FdData.gcmFunction')"
            prop="gcmFunction"
            sort="number"
          />
          <!-- GcmOwner -->
          <Cell v-if="cellIsShow.IsGcmOwner" :label="$t('FdData.gcmOwner')">
            <template slot-scope="scope">
              {{ gcmOwnerById(scope.row.gcmOwner) }}
            </template>
          </Cell>
          <!-- gcmCostRemark -->
          <Cell
            v-if="cellIsShow.IsGcmCostRemark"
            :label="$t('FdData.gcmCostRemark')"
            prop="gcmCostRemark"
          />
        </Cell>
        <Cell fix="right" label="操作" :width="120">
          <template slot-scope="scope">
            <el-link
              style="margin-left: 14px"
              :underline="false"
              @click="rowQuote(scope.index, scope.row)"
            >
              报价
            </el-link>
          </template>
        </Cell>
      </VirtualTable>
    </div>

    <!-- 报价对话框 -->
    <BaseDialog
      v-if="quoteDialogVisible"
      :title="$t('button.edit')"
      :visible.sync="quoteDialogVisible"
      width="700px"
    >
      <EcQuoteEdit
        :base-file-data="inputData"
        :current-row-no="currentRowNo"
        :input-data="currentEditRow"
        @cancel="quoteDialogVisible = false"
        @save="afterQuoteSave"
      />
    </BaseDialog>
    <!--TODO: 设置显示列对话框 -->
    <BaseDialog
      v-if="setDialogVisible"
      title="设置显示列"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <EcCellShowSet
        :cellIsShow="cellIsShow"
        :pageId="pageId"
        @cancel="setDialogVisible = false"
        @saveOperationData="saveOperationData"
      />
    </BaseDialog>
  </div>
</template>
<script>
import EcQuoteEdit from './EcQuoteEdit'

import { fdQuoteCommit, fdQuoteSaveBatch } from '@/api/ecdfc/fd'
import { fileExportFdQuote } from '@/api/ecdfc/file-export'
import XLSX from 'xlsx'

import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'

import ecCell from '@/mixins/ecCell'
import EcCellShowSet from '../../components/EcCellShowSet'

export default {
  name: 'EcQuoteEditPane',
  components: { EcQuoteEdit, VirtualTable, Cell, EcCellShowSet },
  mixins: [ecCell],
  props: {
    inputData: {
      default: () => null,
      type: Object
    },

    shareDataList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 转发对话框可见标识
      quoteDialogVisible: false,
      // 当前修改行
      currentEditRow: {},
      // 当前行号
      currentRowNo: 0,
      // idp token
      idpToken: '',
      // 每一行的图片数据
      picList: [],
      // 图片对话框可见标识
      picDialogVisible: false,
      // 合计信息
      totalResult: {
        totalLen: 0,
        currentLen: 0,
        costDown: 0
      },
      // 正在加载
      isRequesting: false,
      // 未完成的列
      unDoneApproveList: [],
      setDialogVisible: false,
      pageId: 'EcQuoteEditPane',
      cellIsShow: {}
    }
  },
  computed: {
    gcmOwnerById() {
      return gcmOwner => {
        if (gcmOwner && gcmOwner.length) {
          return this.$store.getters['user/getUserNameById'](gcmOwner)
        } else {
          return ''
        }
      }
    },
    costDelta() {
      return scope => {
        const pbmCommitQuote = scope.row.pbmCommitQuote
        return pbmCommitQuote
      }
    }
  },
  methods: {
    rowStyle(index, row) {
      if (this.unDoneApproveList.find(item => item.fdRowId === row.fdRowId)) {
        return {
          backgroundColor: '#ffdada'
        }
      }
    },

    rowQuote(index, row) {
      this.currentRowNo = index + 1
      this.currentEditRow = this.$deepCopy(row)
      this.quoteDialogVisible = true
    },
    // 全部估价提交
    async saveAll() {
      try {
        await this.$confirmBox(this.$t('button.submit'), 'success')
        this.unDoneApproveList = this.shareDataList.filter(
          item =>
            item.pbmCost === null ||
            item.pbmCommitCost === null ||
            item.ec_dfc_row_id === null ||
            item.cost_down === null
        )
        if (this.unDoneApproveList.length > 0) {
          return this.$message({
            message: '存在未报价数据',
            type: 'error',
            duration: 1500
          })
        }
        this.isRequesting = true

        await fdQuoteCommit(
          { fdId: this.inputData.fdId, version: this.inputData.version },
          { msgSuccess: true, msgError: true }
        )
        this.$emit('cancel')
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    // 报价完成之后
    afterQuoteSave() {
      this.quoteDialogVisible = false
      this.$emit('update')
    },

    totalCb(args) {
      this.totalResult = { ...args }
    },

    // 下载
    async rowDown() {
      try {
        await this.$confirmBox(this.$t('button.down'), 'success')
        this.isRequesting = true
        const res = await fileExportFdQuote(
          {
            fdId: this.inputData.fdId,
            version: this.inputData.version
          },
          { downExcelFile: true, msgSuccess: true, msgError: true }
        )
        this.$downFile(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    // 上传数据
    uploadFile() {
      this.$refs['inputfile'].click()
    },
    // 读取文件
    inputfileChange(event) {
      const files = event.target.files

      if (!files) return

      const f = files[0]

      const reader = new FileReader()

      reader.onload = async e => {
        const data = e.target.result

        const workbook = XLSX.read(data, { type: 'array' })

        const sheet = workbook.Sheets[workbook.SheetNames[1]]

        // !ref 默认是表格第一行到最后一行(数据的最后一行)

        const maxColumn = sheet['!ref'].split(':')[1]

        sheet['!ref'] = `A1:${maxColumn}`

        const result = XLSX.utils.sheet_to_json(sheet)

        this.saveUploadList(
          // TODO:
          result.map(item => {
            return {
              fdRowId: item.ec_dfc_row_id || '',
              pbmCost: item.pbmCost || '',
              pbmCommitCost: item.pbmCommitCost || '',
              costDown: item.cost_down || ''
            }
          })
        )

        event.target.value = ''
      }
      reader.readAsArrayBuffer(f)
    },

    // save
    async saveUploadList(list) {
      try {
        this.isRequesting = true

        const uploadList = list.filter(item => String(item.costDown).trim() !== '')

        await fdQuoteSaveBatch(uploadList, { msgSuccess: true, msgError: true })

        this.$emit('update')
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    }
  }
}
</script>
<style lang="scss">
.fd-quote-edit-pane {
  .custom-top {
    width: calc(100% - 17px);
    height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .btn {
      margin-top: 15px;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .custom-bottom {
    position: absolute;
    top: 80px;
    bottom: 0;
    left: 20px;
    right: 25px;
  }
  .upload {
    width: 0;
    display: none;
  }
}
</style>
